<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全球最大交友平台</title>
</head>
<body>
<form onsubmit="return false">
    <textarea name="message" id="message" style="height: 300px;width: 300px"></textarea>
    <input id="button" type="button" value="发送消息" onclick="send(this.form.message.value)"/>
    <textarea id="responseText" style="height: 600px;width: 800px;font-size: 15px" readonly="true"></textarea>
    <input type="button" value="清空" onclick="document.getElementById('responseText').value=''"/>
</form>
</body>

<script>

    document.onkeydown=function(event){
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if(e && e.keyCode==13){
            document.getElementById('button').onclick();
        }
    };

    var socket;
    if(window.WebSocket) {
        socket = new WebSocket("ws://rmn4wg.natappfree.cc/hello");
        //客户端接收到消息
        socket.onmessage=function (ev) {
            var rt=document.getElementById('responseText');
            rt.value = rt.value + "\n" + ev.data;
        }
        //连接开启
        socket.onopen=function (ev) {
            var rt=document.getElementById('responseText');
            rt.value = "连接开启了..."
        }
        //连接关闭
        socket.onclose=function (ev) {
            var rt=document.getElementById('responseText');
            rt.value =   rt.value+"\n"+"连接关闭了"
        }

        function send(msg) {
            if(!window.socket){
                return;
            }
            if(socket.readyState==WebSocket.OPEN) {
                socket.send(msg.trim());
                document.getElementById('message').value = "";
            }else{
                alert("连接未开启")
            }
        }
    }else{
        alert("当前浏览器不支持websocket");
    }
</script>
</html>